package cn.wolfcode.p2p.base.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.wolfcode.base.QueryObject;
import cn.wolfcode.p2p.base.domain.SystemDictionaryItem;
import cn.wolfcode.p2p.base.mapper.SystemDictionaryItemMapper;
import cn.wolfcode.p2p.base.query.SystemDictionaryItemQuery;
import cn.wolfcode.p2p.base.service.ISystemDictionaryItemService;

@Service
@Transactional
public class SystemDictionaryItemServiceImpl implements ISystemDictionaryItemService {
    @Autowired
    private SystemDictionaryItemMapper systemDictionaryItemMapper;
	
	@Transactional(readOnly=true)
	public PageInfo<SystemDictionaryItem> query(QueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
		List<SystemDictionaryItem> list = systemDictionaryItemMapper.selectList(qo);
		return new PageInfo<SystemDictionaryItem>(list);
	}

	@Override
	public void saveOrUpdate(SystemDictionaryItem sdi) {
	    // 如果顺序为空, 则在最大的顺序+1
        if (sdi.getSequence() == null){
            // 判断是否有数据
            int maxSequence = 0;
            int count = systemDictionaryItemMapper.selectCount(new SystemDictionaryItemQuery());

            if (count > 0){
                // 查询最大的
                SystemDictionaryItemQuery qo = new SystemDictionaryItemQuery();
                qo.setParentId(sdi.getParentId());
                maxSequence = systemDictionaryItemMapper.selectMaxSequence(qo);
            }else {

            }
            sdi.setSequence(maxSequence + 1);
        }

		if (sdi.getId() != null){
			systemDictionaryItemMapper.updateById(sdi);
			return;
		}
		systemDictionaryItemMapper.insert(sdi);
	}

	@Override
	public List<SystemDictionaryItem> listItemByDicSn(String sn) {
		return systemDictionaryItemMapper.selectItemByDicSn(sn);
	}
}
